import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Select, DatePicker, Button, Spin, Empty, Statistic, Divider } from 'antd';
import { ArrowLeftOutlined, DownloadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
// 假设我们使用Echarts进行图表展示
import ReactECharts from 'echarts-for-react';

// 引入API
import { listSalaries } from '../../../api/salary';

const { Option } = Select;
const { RangePicker } = DatePicker;

const SalaryStatistics = () => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [salaryData, setSalaryData] = useState([]);
    const [dateRange, setDateRange] = useState([dayjs().subtract(11, 'months'), dayjs()]);
    const [departmentFilter, setDepartmentFilter] = useState(null);
    
    // 统计数据
    const [totalAmount, setTotalAmount] = useState(0);
    const [averageSalary, setAverageSalary] = useState(0);
    const [employeeCount, setEmployeeCount] = useState(0);
    const [maxSalary, setMaxSalary] = useState(0);

    useEffect(() => {
        fetchSalaryData();
    }, []);

    // 获取薪资数据
    const fetchSalaryData = async () => {
        if (!dateRange || dateRange.length !== 2) {
            return;
        }

        setLoading(true);
        try {
            const startDate = dateRange[0].format('YYYY-MM');
            const endDate = dateRange[1].format('YYYY-MM');
            
            const params = {
                startDate,
                endDate,
                pageSize: 1000, // 获取足够多的数据进行统计
                department: departmentFilter
            };
            
            const response = await listSalaries(params);
            const data = response.data || [];
            setSalaryData(data);
            
            // 计算统计数据
            calculateStatistics(data);
        } catch (error) {
            console.error('获取薪资统计数据失败:', error);
        } finally {
            setLoading(false);
        }
    };

    // 计算统计数据
    const calculateStatistics = (data) => {
        if (!data || data.length === 0) {
            setTotalAmount(0);
            setAverageSalary(0);
            setEmployeeCount(0);
            setMaxSalary(0);
            return;
        }
        
        // 计算总支出
        const total = data.reduce((sum, item) => sum + (item.netSalary || 0), 0);
        setTotalAmount(total);
        
        // 计算员工数量
        const uniqueEmployees = new Set(data.map(item => item.userId));
        setEmployeeCount(uniqueEmployees.size);
        
        // 计算平均薪资
        setAverageSalary(total / data.length);
        
        // 计算最高薪资
        const max = Math.max(...data.map(item => item.netSalary || 0));
        setMaxSalary(max);
    };

    // 处理日期范围变化
    const handleDateRangeChange = (dates) => {
        setDateRange(dates);
    };

    // 处理部门筛选变化
    const handleDepartmentChange = (value) => {
        setDepartmentFilter(value);
    };

    // 处理搜索
    const handleSearch = () => {
        fetchSalaryData();
    };

    // 返回列表
    const handleBack = () => {
        navigate('/salary');
    };

    // 导出报表
    const handleExport = () => {
        // 实现导出功能
    };

    // 月度薪资趋势图表配置
    const getMonthlySalaryOption = () => {
        // 按月份分组数据
        const monthlyData = {};
        salaryData.forEach(item => {
            const monthKey = `${item.year}-${item.month.toString().padStart(2, '0')}`;
            if (!monthlyData[monthKey]) {
                monthlyData[monthKey] = [];
            }
            monthlyData[monthKey].push(item);
        });
        
        // 计算每月总薪资和平均薪资
        const months = Object.keys(monthlyData).sort();
        const totalSalaries = months.map(month => {
            return monthlyData[month].reduce((sum, item) => sum + (item.netSalary || 0), 0);
        });
        
        const avgSalaries = months.map(month => {
            const total = monthlyData[month].reduce((sum, item) => sum + (item.netSalary || 0), 0);
            return monthlyData[month].length > 0 ? total / monthlyData[month].length : 0;
        });
        
        return {
            title: {
                text: '月度薪资趋势'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['总薪资支出', '平均薪资']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: months.map(m => {
                    const [year, month] = m.split('-');
                    return `${year}年${parseInt(month)}月`;
                })
            },
            yAxis: [
                {
                    type: 'value',
                    name: '总薪资支出',
                    axisLabel: {
                        formatter: '{value} 元'
                    }
                },
                {
                    type: 'value',
                    name: '平均薪资',
                    axisLabel: {
                        formatter: '{value} 元'
                    }
                }
            ],
            series: [
                {
                    name: '总薪资支出',
                    type: 'line',
                    data: totalSalaries,
                    yAxisIndex: 0,
                    smooth: true
                },
                {
                    name: '平均薪资',
                    type: 'line',
                    data: avgSalaries,
                    yAxisIndex: 1,
                    smooth: true
                }
            ]
        };
    };

    // 部门薪资分布图表配置
    const getDepartmentSalaryOption = () => {
        // 按部门分组数据
        const departmentData = {};
        salaryData.forEach(item => {
            const deptName = item.user?.department?.name || '未分配';
            if (!departmentData[deptName]) {
                departmentData[deptName] = [];
            }
            departmentData[deptName].push(item);
        });
        
        // 计算每个部门的总薪资和平均薪资
        const departments = Object.keys(departmentData);
        const totalSalaries = departments.map(dept => {
            return departmentData[dept].reduce((sum, item) => sum + (item.netSalary || 0), 0);
        });
        
        const avgSalaries = departments.map(dept => {
            const total = departmentData[dept].reduce((sum, item) => sum + (item.netSalary || 0), 0);
            return departmentData[dept].length > 0 ? total / departmentData[dept].length : 0;
        });
        
        return {
            title: {
                text: '部门薪资分布'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['总薪资支出', '平均薪资']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: departments
            },
            yAxis: [
                {
                    type: 'value',
                    name: '总薪资支出',
                    axisLabel: {
                        formatter: '{value} 元'
                    }
                },
                {
                    type: 'value',
                    name: '平均薪资',
                    axisLabel: {
                        formatter: '{value} 元'
                    }
                }
            ],
            series: [
                {
                    name: '总薪资支出',
                    type: 'bar',
                    data: totalSalaries,
                    yAxisIndex: 0
                },
                {
                    name: '平均薪资',
                    type: 'line',
                    data: avgSalaries,
                    yAxisIndex: 1,
                    smooth: true
                }
            ]
        };
    };

    // 薪资组成分析图表配置
    const getSalaryCompositionOption = () => {
        // 计算各项薪资组成的总和
        const baseSalaryTotal = salaryData.reduce((sum, item) => sum + (item.baseSalary || 0), 0);
        const bonusTotal = salaryData.reduce((sum, item) => sum + (item.bonus || 0), 0);
        const overtimeTotal = salaryData.reduce((sum, item) => sum + (item.overtime || 0), 0);
        const subsidyTotal = salaryData.reduce((sum, item) => sum + (item.subsidy || 0), 0);
        const otherIncomeTotal = salaryData.reduce((sum, item) => sum + (item.otherIncome || 0), 0);
        
        return {
            title: {
                text: '薪资组成分析'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 10,
                data: ['基本工资', '绩效奖金', '加班费', '补贴', '其他收入']
            },
            series: [
                {
                    name: '薪资组成',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: baseSalaryTotal, name: '基本工资' },
                        { value: bonusTotal, name: '绩效奖金' },
                        { value: overtimeTotal, name: '加班费' },
                        { value: subsidyTotal, name: '补贴' },
                        { value: otherIncomeTotal, name: '其他收入' }
                    ]
                }
            ]
        };
    };

    return (
        <div className="salary-statistics-container">
            <Card
                title="薪资统计分析"
                extra={
                    <div>
                        <Button icon={<ArrowLeftOutlined />} onClick={handleBack} style={{ marginRight: 8 }}>
                            返回
                        </Button>
                        <Button icon={<DownloadOutlined />} onClick={handleExport}>
                            导出报表
                        </Button>
                    </div>
                }
            >
                <div className="filter-container" style={{ marginBottom: 24 }}>
                    <Row gutter={16} align="middle">
                        <Col>
                            <span>时间范围：</span>
                            <RangePicker 
                                picker="month" 
                                value={dateRange}
                                onChange={handleDateRangeChange}
                                style={{ marginRight: 16 }}
                            />
                        </Col>
                        <Col>
                            <span>部门：</span>
                            <Select
                                allowClear
                                placeholder="选择部门"
                                style={{ width: 200, marginRight: 16 }}
                                onChange={handleDepartmentChange}
                                value={departmentFilter}
                            >
                                <Option value="hr">人力资源部</Option>
                                <Option value="tech">技术部</Option>
                                <Option value="finance">财务部</Option>
                                <Option value="marketing">市场部</Option>
                                <Option value="sales">销售部</Option>
                            </Select>
                        </Col>
                        <Col>
                            <Button type="primary" onClick={handleSearch}>
                                查询
                            </Button>
                        </Col>
                    </Row>
                </div>

                <Spin spinning={loading}>
                    {salaryData.length > 0 ? (
                        <div className="statistics-content">
                            {/* 统计概览 */}
                            <Row gutter={24} className="statistics-overview">
                                <Col span={6}>
                                    <Statistic 
                                        title="薪资总支出" 
                                        value={totalAmount} 
                                        precision={2}
                                        prefix="¥"
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic 
                                        title="平均薪资" 
                                        value={averageSalary} 
                                        precision={2}
                                        prefix="¥"
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic 
                                        title="员工数量" 
                                        value={employeeCount}
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic 
                                        title="最高薪资" 
                                        value={maxSalary} 
                                        precision={2}
                                        prefix="¥"
                                    />
                                </Col>
                            </Row>

                            <Divider />

                            {/* 图表展示 */}
                            <div className="statistics-charts">
                                <Row gutter={[24, 24]}>
                                    <Col span={24}>
                                        <ReactECharts 
                                            option={getMonthlySalaryOption()} 
                                            style={{ height: 400 }}
                                        />
                                    </Col>
                                    <Col span={12}>
                                        <ReactECharts 
                                            option={getDepartmentSalaryOption()} 
                                            style={{ height: 400 }}
                                        />
                                    </Col>
                                    <Col span={12}>
                                        <ReactECharts 
                                            option={getSalaryCompositionOption()} 
                                            style={{ height: 400 }}
                                        />
                                    </Col>
                                </Row>
                            </div>
                        </div>
                    ) : (
                        <Empty description="暂无薪资统计数据" />
                    )}
                </Spin>
            </Card>
        </div>
    );
};

export default SalaryStatistics;